/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/



import style from './index.less';
import React, { useState } from 'react';
import IAutoButton from '@/components/soa/IAutoButton';
import {
  Card,
  Form,
  Input,
  InputNumber,
  message,
  Row,
  Space,
  Upload,
  Image,
  TableColumnsType,
  Modal,
  Col,
  Popconfirm,
} from 'antd';
import { UploadFile } from 'antd/es/upload/interface';

import { createIcon, deleteIcon, editIcon, editIconStatus, getIconList } from '@/services/soa/icon';
import {
  customHandle,
  getDateTime,
  imageBeforeUploadHandle,
  refreshOrGoPrePage,
} from '@/utils/soa/utils';
import { useRequest, useAntdTable } from 'ahooks';
import { PlusOutlined } from '@ant-design/icons';
import IAutoTable from '@/components/soa/IAutoTable';
import { IIconItem, IIconStatus } from '@/types/icon';
import IAutoStatus from '@/components/soa/IAutoStatus';
import { DELETE_MESSAGE } from '@/utils/soa/constant';
import { iconBackgroundReg } from '@/utils/soa/check';

const { useForm } = Form;
const { TextArea } = Input;
const { Item } = Form;

export default (props:any) => {
  const {location:{pathname}} = props;
  const [recordData, setRecordData] = useState<IIconItem | undefined>(undefined);
  const [fileUuid, setFileUuid] = useState<string>('');
  const [imageFileList, setImageFileList] = useState<UploadFile[]>([]);
  const [url, setUrl] = useState('');
  const [open, setOpen] = useState(false);
  const [form] = useForm();

  const columns: TableColumnsType<IIconItem> = [
    {
      title: '编号',
      dataIndex: 'index',
      width: 50,
    },
    {
      title: 'UUID',
      dataIndex: 'uuid',
      width: 300,
    },
    {
      title: '名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      title: '图标',
      dataIndex: 'url',
      width: 100,
      render: (text) => {
        return (
          <Image
            style={{
              objectFit: 'contain',
              width: 30,
              height: 30,
              borderRadius: '4px',
            }}
            preview={false}
            src={text}
          />
        );
      },
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '排序号',
      dataIndex: 'weight',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (text) => IAutoStatus(text),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180,
      render: (text) => getDateTime(text),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 180,
      render: (_, record) => (
        <Space>
          <Popconfirm
            title={`是否确认${record.status === 0 ? '停用' : '启用'}?`}
            onConfirm={() => {
              setRecordData(record);
              handelStatusIcon(record);
            }}
          >
            <IAutoButton pathname={pathname} auth={"icon_doEnable"}>
              {record.status === 0 ? <span>停用</span> : <span>启用</span>}
            </IAutoButton>
          </Popconfirm>
          <IAutoButton disabled={record.status === 0} onClick={() => handelEditIcon(record)} pathname={pathname} auth={"icon_doEdit"}>
            修改
          </IAutoButton>
          <Popconfirm
            title={DELETE_MESSAGE}
            onConfirm={() => {
              deleteIconResponse.run(record.id);
            }}
          >
            <IAutoButton disabled={record.status === 0} pathname={pathname} auth={"icon_doDel"}>删除</IAutoButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const closeHandle = () => {
    form.resetFields();
    setOpen(false);
  };

  const { tableProps, refresh, params } = useAntdTable(getIconList);

  const createIconResponse = useRequest(createIcon, {
    manual: true,
    onSuccess: (res) => {
      if (res.statusCode === '0') {
        message.success('保存成功');
        closeHandle();
        refresh();
      }
    },
  });

  const editIconResponse = useRequest(editIcon, {
    manual: true,
    onSuccess: (res) => {
      if (res.statusCode === '0') {
        message.success('修改成功');
        closeHandle();
        refresh();
      }
    },
  });

  const deleteIconResponse = useRequest(deleteIcon, {
    manual: true,
    onSuccess: (res) => {
      if (res.statusCode === '0') {
        message.success('删除成功');
        refreshOrGoPrePage({ tableProps, params });
      }
    },
  });

  const editIconStatusResponse = useRequest(editIconStatus, {
    manual: true,
    onSuccess: (res) => {
      if (res.statusCode === '0') {
        message.success('修改成功');
        closeHandle();
        refresh();
      }
    },
  });

  const handelStatusIcon = (record: IIconItem) => {
    editIconStatusResponse.run(Number(!record.status) as IIconStatus, record.id);
  };

  const handelEditIcon = (record: IIconItem) => {
    console.log(record);
    setRecordData(record);
    setOpen(true);

    form.setFieldsValue({
      name: record?.name,
      description: record?.description,
      status: record?.status,
      weight: record?.weight,
      icon: { uid: record.fileUuid, url: record.url, name: '' },
    });

    setImageFileList([
      {
        uid: record.fileUuid,
        url: record.url,
        name: '',
      },
    ]);
    setFileUuid(record.fileUuid);
    setUrl(record.url);
  };

  const openHandle = () => {
    setRecordData(undefined);
    form.resetFields();
    setImageFileList([]);
    setOpen(true);
  };

  const handelCreateIcon = () => {
    form.validateFields().then(() => {
      const { name, weight, description } = form.getFieldsValue();

      const data = {
        name: name,
        weight: weight,
        description: description,
        fileUuid: fileUuid,
        url: url,
      };

      if (recordData) {
        editIconResponse.run(data, recordData.id);
      } else {
        createIconResponse.run(data);
      }
    });
  };

  const onRemoveImage = (
    file: UploadFile,
    list: UploadFile[],
    callback: (result: UploadFile[]) => void,
  ) => {
    const index = list.indexOf(file);
    const newFileList = list.slice();
    newFileList.splice(index, 1);
    callback(newFileList);
    form.setFieldsValue({
      icon: undefined,
    });
  };

  return (
    <Card className={style.main}>
      <Row justify={'end'} className={style.newButton}>
        <Col>
          <IAutoButton size="small" buttonType={"form"} icon={<PlusOutlined />} type={'primary'} onClick={openHandle} pathname={pathname} auth={"icon_doAdd"}>
            新增
          </IAutoButton>
        </Col>
      </Row>

      <IAutoTable columns={columns} tableProps={tableProps} />
      <Modal
        title={recordData ? '修改图标' : '新增图标'}
        visible={open}
        onOk={form.submit}
        onCancel={closeHandle}
      >
        <Form form={form} initialValues={{ weight: 0 }} onFinish={handelCreateIcon}>
          <Item
            name="name"
            label={'名称'}
            rules={[
              {
                required: true,
                whitespace: true,
                message: '请输入名称',
              },
              {
                pattern: iconBackgroundReg,
                message: '名称需满足中文、英文、数字，长度2~12位',
              },
            ]}
          >
            <Input
              // size="large"
              allowClear
              placeholder={'请输入名称'}
              maxLength={12}
              //   className={styles.itemWidth}
            />
          </Item>

          <Item
            label="图标"
            name="icon"
            rules={[
              {
                required: true,
                message: '请上传icon图',
              },
            ]}
          >
            <Upload
              multiple={false}
              listType="picture-card"
              onRemove={(file) =>
                onRemoveImage(file, imageFileList, (result: UploadFile[]) => {
                  setImageFileList(result);
                })
              }
              fileList={imageFileList}
              beforeUpload={(file) => imageBeforeUploadHandle(file)}
              customRequest={(file) =>
                customHandle(file, 'SCENE_PUBLIC', (info: any, r: any) => {
                  form.setFieldsValue({
                    icon: {
                      uid: r.data.uuid,
                      url: r.data.publicUrl,
                      name: info?.file?.name,
                      size: info?.file?.size,
                    },
                  });
                  setImageFileList([
                    {
                      uid: r.data.uuid,
                      url: r.data.publicUrl,
                      name: info?.file?.name,
                      size: info?.file?.size,
                    },
                  ]);
                  setFileUuid(r.data.uuid);
                  setUrl(r.data.publicUrl);
                })
              }
              maxCount={1}
            >
              {imageFileList.length >= 1 ? null : (
                <div>
                  <PlusOutlined />
                </div>
              )}
            </Upload>
            <Item noStyle>
              <span>上传文件（jpg/jpeg/png），大小 &lt;{5}M</span>
            </Item>
          </Item>
          <Item
            name="description"
            label={'描述'}
            rules={[
              {
                required: true,
                // whitespace: true,
                message: '请输入描述',
              },
            ]}
          >
            <TextArea allowClear placeholder={'请输入描述'} maxLength={128} />
          </Item>
          <Item
            name="weight"
            label={'排序号'}
            rules={[
              {
                required: true,
                message: '请输入排序号',
              },
            ]}
          >
            <InputNumber min={0} max={999} />
          </Item>
        </Form>
      </Modal>
    </Card>
  );
};
